#ifndef YHAIDA_TIMERQUEUE_H
#define YHAIDA_TIMERQUEUE_H
#include "../base/Utils.h"
#include "../datetime/Timestamp.h"
#include "Channel.h"
#include "Callbacks.h"
#include "../mutex/MutexLock.h"
#include "../logging/Logging.h"
#include <vector>
#include <set>
#include <memory>
#include <sys/timerfd.h>
#include <iterator>
#include <type_traits>
#include <algorithm>
namespace yhaida
{
    class EventLoop;
    class Timer;
    class TimerID;

    class TimerQueue : Utils::nocapyable
    {
    public:
        typedef std::pair<Timestamp, Timer *> TimerListNode;
        typedef std::set<TimerListNode> TimeList; // set是有序

        typedef std::pair<Timer *, int64_t> ActiveTimer;
        typedef std::set<ActiveTimer> ActiveTimerSet;

    public:
        TimerQueue(EventLoop *loop);
        ~TimerQueue();

        TimerID addTimer(TimerCallback fuc, Timestamp when, double interval);

        void cancel(TimerID timerID);

    private:
        void addTimerInLoop(Timer *timer);
        void cancelTimerInLoop(TimerID timerID);
        void handleRead();
        // 1.得到过期的计时器
        std::vector<TimerListNode> getExpired(Timestamp now);
        // 2.重置计时器(处理已经过期的计时器，是要重新repeat还是丢弃)
        void reset(const std::vector<TimerListNode> &expired, Timestamp now);
        bool insert(Timer *timer);

        EventLoop *_mainEventLoop;
        const int _timeFd;
        Channel _timeChannel;
        TimeList _timers;

        bool _callingExpiredTimers; 
        ActiveTimerSet _activeTimers;//数量与_timers一样多，只是TimeList按照时间顺序排列，ActiveTimerSet按照地址排列
        ActiveTimerSet _cancelingTimers;
    };
}
#endif